﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading;
using System.Windows;
using System.Windows.Media;
using MC.Phone.Ads.Provider;
using MC.Phone.Ads.Utils;
using SmaatoAdControl = SOMAWP7.SomaAdViewer;

namespace MC.Phone.Ads.Smaato
{
    public class SmaatoAdProvider : BaseAdProvider
    {
        public static readonly DependencyProperty AdSpaceProperty =
            DependencyProperty.Register("AdSpace", typeof (int), typeof (SmaatoAdProvider), null);

        public static readonly DependencyProperty PublisherProperty =
            DependencyProperty.Register("Publisher", typeof (int), typeof (SmaatoAdProvider), null);

        private WeakEventListener<SmaatoAdProvider, object, EventArgs> _adClickListener;
        private WeakEventListener<SmaatoAdProvider, object, string, string> _adErrorListener;
        private WeakEventListener<SmaatoAdProvider, object, EventArgs> _newAdListener;

        [Category("Ad")]
        public int AdSpace
        {
            get { return (int) GetValue(AdSpaceProperty); }
            set { SetValue(AdSpaceProperty, value); }
        }

        [Category("Ad")]
        public int Publisher
        {
            get { return (int) GetValue(PublisherProperty); }
            set { SetValue(PublisherProperty, value); }
        }

        #region IAdProvider Members

        public override string Name
        {
            get { return "Smaato"; }
        }

        public override FrameworkElement ProvideAd()
        {
            var backgroundBrush = Application.Current.Resources["StandardApplicationBackgroundBrush"] as SolidColorBrush;
            string backgroundColor = string.Empty;
            if (backgroundBrush != null)
                backgroundColor = string.Format("#{0:x2}{1:x2}{2:x2}", backgroundBrush.Color.R, backgroundBrush.Color.G,
                                                backgroundBrush.Color.B);
            var control = new SmaatoAdControl
                                        {
                                            Adspace = IsTest ? 0 : AdSpace,
                                            Pub = IsTest ? 0 : Publisher,
                                            Countrycode = CountryCode,
                                            PopupAd = true,
                                            BackgroundColor = backgroundColor,
                                        };
            _adClickListener = new WeakEventListener<SmaatoAdProvider, object, EventArgs>(this)
                                   {
                                       OnEventAction = (instance, source, args) => instance.ControlAdClick(),
                                       OnDetachAction = weak => control.AdClick -= weak.OnEvent
                                   };
            control.AdClick += _adClickListener.OnEvent;
            _adErrorListener = new WeakEventListener<SmaatoAdProvider, object, string, string>(this)
                                   {
                                       OnEventAction =
                                           (instance, source, args, args2) => instance.ControlAdError(args, args2),
                                       OnDetachAction = weak => control.AdError -= weak.OnEvent
                                   };
            control.AdError += _adErrorListener.OnEvent;
            _newAdListener = new WeakEventListener<SmaatoAdProvider, object, EventArgs>(this)
                                 {
                                     OnEventAction =
                                         (instance, source, args) => instance.ControlNewAdAvailable(source, args),
                                     OnDetachAction = weak => control.NewAdAvailable -= weak.OnEvent
                                 };
            control.NewAdAvailable += _newAdListener.OnEvent;

            control.NewAdAvailable += ControlNewAdAvailable;
            control.StartAds();
            return control;
        }

        public override void Clean()
        {
            _adClickListener = _adClickListener.DetachToNull();
            _adErrorListener = _adErrorListener.DetachToNull();
            _newAdListener = _newAdListener.DetachToNull();
        }

        #endregion

        private void ControlNewAdAvailable(object sender, EventArgs e)
        {
            OnNewAd();
        }

        private void ControlAdError(string errorcode, string errordescription)
        {
            if (errorcode == "42")
            {
                OnNoAd();
            }
            else
            {
                OnAdError(new Exception(string.Format("{0}:{1}", errorcode, errordescription)));
            }
        }

        private void ControlAdClick()
        {
            OnAdEngaged();
        }

        
#if DEBUG
        ~SmaatoAdProvider()
        {
            Debug.WriteLine( Thread.CurrentThread.ManagedThreadId + "--Finalizing " + GetType().FullName);
        }
#endif
    }
}